package com.lzx.adx.report.task;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.PageUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.DateUtils;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.CommonLocalCache;
import com.lzx.adx.report.cache.OcpxAccountLocalCache;
import com.lzx.adx.report.cache.ProductConfigLocalCache;
import com.lzx.adx.report.dto.OcpxAccountDTO;
import com.lzx.adx.report.dto.ProductConfigDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.dto.YunxuanOrderDTO;
import com.lzx.adx.report.dto.yunxuan.GoodsInfo;
import com.lzx.adx.report.dto.yunxuan.YunXuanDTO;
import com.lzx.adx.report.dto.yunxuan.YunXuanResponse;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.service.YunxuanOrderService;
import com.lzx.adx.report.support.context.v3.CallBackV3Context;
import com.lzx.adx.report.support.strategy.v3.media.AbstractChannel;
import com.lzx.adx.report.util.YunXuanHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Objects;

@Component
@RestController
@RequestMapping("task")
@Slf4j
public class YunXuanTask implements ITask{


    @Autowired
    private YunxuanOrderService yunxuanOrderService;

    @Autowired
    private ReportMapper reportMapper;

    @Autowired
    private ReportService reportService;

    @Resource
    private CallBackV3Context callBackV3Context;


    @RequestMapping("/yxuan")
    @Override
    public void run(String params) throws Exception {
        log.info("进行云选-上报处理-begin");
        YunXuanResponse dataListPage = YunXuanHelper.getDataListPage(1);
        if(Objects.isNull(dataListPage)){
            log.info("腾讯云选状态异常。。。");
            return;
        }
        //获取订单列表的数据
        List<YunXuanDTO> dataList = dataListPage.getDataList();
        if(CollectionUtil.isEmpty(dataList)){
            log.info("腾讯云选暂无订单数据。。。");
            return;
        }
        //进行数据分页
        Integer totalPage= PageUtil.totalPage(dataListPage.getTotalCount(),50);
        if(totalPage>1){
            for (int i=1;i<=totalPage;i++){
                YunXuanResponse dataListPage1 = YunXuanHelper.getDataListPage(i);
                //处理核心数据
                handerCoreData(dataListPage1.getDataList());
            }
        }else{
            handerCoreData(dataList);
        }
    }


    /**
     * 处理核心数据
     * @param dataList
     */
    private void handerCoreData(List<YunXuanDTO> dataList) {

        for (YunXuanDTO yunXuanDTO : dataList) {

            try {
                handOrderData(yunXuanDTO);
            }catch (Exception e) {
              log.error("订单号处理异常了{}",yunXuanDTO.getExternal_order_id());
            }

        }

    }

    private void handOrderData(YunXuanDTO yunXuanDTO) {
        //根据订单编号查询数据
        log.info("订单id[{}]正在处理云选小程序订单数据[{}]", yunXuanDTO.getExternal_order_id(), JSONObject.toJSONString(yunXuanDTO));
        YunxuanOrderDTO detail = yunxuanOrderService.getDetail(yunXuanDTO.getExternal_order_id());
        Integer handStatus=0;
        if(Objects.nonNull(detail)){
            detail.setOrderStatus(yunXuanDTO.getOrder_status());
            detail.setRemitStatus(yunXuanDTO.getRemit_status());
            //佣金累积计算
            detail.setTotalCommission(calculateCommission(yunXuanDTO));
            detail.setUTime(new Date());
            yunxuanOrderService.update(detail);
            handStatus=detail.getHandStatus();
        }else{
            YunxuanOrderDTO entity = reportMapper.toReport(yunXuanDTO);
            entity.setCTime(new Date());
            entity.setUTime(new Date());
            //获取广告位ID
            entity.setTxCpsId(yunXuanDTO.getGoods_info().get(0).getChan_info().get(0).getTx_cps_id());
            //佣金累积计算
            Long l = calculateCommission(yunXuanDTO);
            entity.setTotalCommission(l);
            entity.setGoodsJson(JSONObject.toJSONString(yunXuanDTO.getGoods_info()));
            //设置未处理
            entity.setHandStatus(1);
            yunxuanOrderService.save(entity);
            handStatus=1;
        }

        //订单已回传处理过，就跳过这个订单
        if(handStatus.equals(2)){
            return;
        }
        //2.开启匹配回传点击
        String txCpsId = yunXuanDTO.getGoods_info().get(0).getChan_info().get(0).getTx_cps_id();
        String orderTime = DateUtils.timeStamptoDateStr(yunXuanDTO.getPayed_time(), "yyyyMMddHH");
        ReportDTO newData = reportService.getNewData(txCpsId, orderTime);
        log.info("腾讯云选广告位ID{},订单号为{}",txCpsId, yunXuanDTO.getExternal_order_id());
        //3.
        if(Objects.isNull(newData)){
            YunxuanOrderDTO yunxuanOrderDTO=new YunxuanOrderDTO();
            yunxuanOrderDTO.setId(yunXuanDTO.getExternal_order_id());
            yunxuanOrderDTO.setHandStatus(3);
            yunxuanOrderService.update(yunxuanOrderDTO);
            return;
        }

        //获取点击数据
        String cid = yunXuanDTO.getGoods_info().get(0).getChan_info().get(0).getCid();
        newData.setRequestId(cid);
        log.info("腾讯云选广告位ID{},订单号为{},对应的点击为{}",txCpsId, yunXuanDTO.getExternal_order_id(),newData.getBizRequestId());
        //4.账户
        OcpxAccountDTO ocpxAccountDTO= OcpxAccountLocalCache.getInstance().get(txCpsId);

        AbstractChannel abstractReport = callBackV3Context.getCallBack(ocpxAccountDTO.getMediaChannel());
        ProductConfigDTO productConfigDTO = ProductConfigLocalCache.getInstance().get(ocpxAccountDTO.getProductChannel());
        String time = String.valueOf(System.currentTimeMillis());
        ResponseEntity callback = abstractReport.callback(newData, ocpxAccountDTO, productConfigDTO.getDefaultType(), time);

        if(callback.getStatusCode().equals(HttpStatus.OK)){
            //更新状态为已处理
            YunxuanOrderDTO yunxuanOrderDTO=new YunxuanOrderDTO();
            yunxuanOrderDTO.setId(yunXuanDTO.getExternal_order_id());
            yunxuanOrderDTO.setHandStatus(2);
            yunxuanOrderService.update(yunxuanOrderDTO);

            String timeNext = String.valueOf(YunXuanHelper.getDelayCurrentTime());
            log.info("缓存入库时间{}",timeNext);
            CommonLocalCache.getInstance().put("yunXuanStime",timeNext);
        }
    }

    private Long calculateCommission(YunXuanDTO yunXuanDTO) {
        List<GoodsInfo> goodsInfo = yunXuanDTO.getGoods_info();
        Long total = goodsInfo.stream().map(c -> c.getThird_promotion_info()).map(d -> d.getPredict_commission_fee()).reduce(Long::sum).orElse(0L);
        return total;
    }

}
